<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
 	https://open.huolala.cn/#/doc/api?menu=9&type=2&id=5
*/
namespace jy_huolala;
defined('BY_JYA') or exit('error');
class huo_api extends \plugin{
	//发起http请求
	public function request($api_method,$post=array(),$city_id='',$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$basic=plugin('jy_huolala')->plugin_setting('basic');
		if(!$basic['app_key'] || !$basic['app_secret']){
			exi('应用app_key,应用app_secret未设置！','error');
		}
		$rurl=$basic['type']?'https://openapi.huolala.cn/v1':'https://openapi-pre.huolala.cn/v1';
		$post['api_method']=$api_method;
		$post['api_version']='1.0';
		$post['app_key']=$basic['app_key'];
		$post['nonce_str']=random(32);
		$post['timestamp']=time();
		if($basic['expire'] && $basic['expire']<TIMESTAMP+24*3600){
			$basic['access_token']=$this->getAccessToken($basic);
		}
		if(!$basic['access_token'] || $basic['expire']<TIMESTAMP){
			exi('货拉拉令牌失效, 请联系管理员授权刷新！','error');
		}
		if($city_id){
		  $post['city_id']=$city_id;
		}
		$post['access_token']=$basic['access_token'];
		$post['signature']=$this->md5_sign($post,$basic['app_secret']);
		//file_put_contents(ROOT_D.'/1.txt',ijson_encode($post));
		if($isjson){
			$headers = array('Content-Type' => 'application/json');
			$result=cfc('http')->ihttp_json($rurl,$post);
		}elseif($isrequest){
			$result=cfc('http')->ihttp_request($rurl,$post);
		}elseif($post){
			$result=cfc('http')->ihttp_post($rurl,$post);
		}else{
			$result=cfc('http')->ihttp_get($rurl);
		}
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if($data['errcode']){
			$message=$this->error_code($data['errcode']).' '.$data['errmsg'].' '.$data['errcode'];
			if($return_error || $_SESSION['this']=='custom'){
				//return error($message);
			}else{
				//exi($message,'error');
			}
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			$message='访问微信接口错误，以下为原始数据：'.$result['content'];
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	public function getAccessToken($basic=array(),$noexi=0){//获取access_token
		global $_AR;
		$noexi=$noexi?:$_SESSION['noexi'];
		if(!$basic['access_token'] || $basic['expire']<TIMESTAMP){
			exi('货拉拉令牌失效, 请联系管理员授权刷新！','error');
		}
		if(!$basic['app_key'] || !$basic['app_secret']){
			return false;
		}else{
			if($basic['type']){
				$url = "https://open.huolala.cn/oauth/token?grant_type=refresh_token&client_id=".$basic['app_key']."&refresh_token=".$basic['refresh_token']."&isSandbox=false";
			}else{
				$url = "https://open-pre.huolala.cn/oauth/token?grant_type=refresh_token&client_id=".$basic['app_key']."&refresh_token=".$basic['refresh_token']."&isSandbox=true";
			}
		}
		$content = cfc('http')->ihttp_request($url);
		if(is_error($content) && !$noexi){
			exi('刷新令牌失败, 请稍后重试！错误详情：'.$content['message'],'error');
		}
		$res = @json_decode($content['content'], true);
		$token=$res['data'];
		if(empty($res) || empty($token['access_token']) && !$noexi) {
			exi('刷新令牌失败, 请稍后重试！错误代码-' .$res['ret'].'，错误信息-' .$res['msg'],'error');
		}
		$basic['access_token'] = $token['access_token'];
		$basic['auth_mobile'] = $token['auth_mobile'];
		$basic['refresh_token'] = $token['refresh_token'];
		$basic['auth_end_time'] = $token['auth_end_time'];
		$basic['expire'] = strtotime($token['auth_end_time']);
		$this->plugin_setting('basic',$basic);
		return $basic['access_token'];
	}
	public function gettoken($code='',$noexi=0){//获取access_token
		if(!$code){
			exi('code为空！','error');
		}
		$noexi=$noexi?:$_SESSION['noexi'];
		$basic=plugin('jy_huolala')->plugin_setting('basic');
		if(!$basic['app_key'] || !$basic['app_secret']){
			exi('应用app_key,应用app_secret未设置！','error');
		}
		if(!$basic['app_key'] || !$basic['app_secret']){
			return false;
		}else{
			if($basic['type']){
				$url = "https://open.huolala.cn/oauth/token?grant_type=authorization_code&client_id=".$basic['app_key']."&code=".$code."&isSandbox=false";
			}else{
				$url = "https://open-pre.huolala.cn/oauth/token?grant_type=authorization_code&client_id=".$basic['app_key']."&code=".$code."&isSandbox=true";
			}
		}
		$content = cfc('http')->ihttp_request($url);
		if(is_error($content) && !$noexi){
			exi('刷新令牌失败, 请稍后重试！错误详情：'.$content['message'],'error');
		}
		$res = @json_decode($content['content'], true);
		$token=$res['data'];
		if(empty($res) || empty($token['access_token']) && !$noexi) {
			exi('刷新令牌失败, 请稍后重试！错误代码-' . $res['ret'] . '，错误信息-' . $res['msg'],'error');
		}
		$basic['access_token'] = $token['access_token'];
		$basic['auth_mobile'] = $token['auth_mobile'];
		$basic['refresh_token'] = $token['refresh_token'];
		$basic['auth_end_time'] = $token['auth_end_time'];
		$basic['expire'] = strtotime($token['auth_end_time']);
		//file_put_contents(ROOT_D.'/1.TXT',ijson_encode($basic));
		plugin('jy_huolala')->plugin_setting('basic',$basic);
		return $basic['access_token'];
	}
	//获取城市
	public function get_city() {
		$api_method = 'e-city-list';
		$res=$this->request($api_method,'');
		//print_r($res);exit;
		if($res['ret']){
			exi('获取城市失败：'.$res['ret'].','.$res['msg'],'error');
		}
		return $res['data'];
	}
	//获取城市车型
	public function get_che($city_id=0) {
		$api_method = 'e-city-info';
		$res=$this->request($api_method,'',$city_id);
		//print_r($res);exit;
		if($res['ret']){
			exi('获取城市车型失败：'.$res['ret'].','.$res['msg'],'error');
		}
		return $res['data'];
	}
	//计价
	public function get_price($orders,$merchid=0){
		$api_method = 'e-price-calculate';
		$basic=plugin('jy_huolala')->plugin_setting('basic');
		if(!$basic['city_id']){
			exi('货拉拉接口还未设置城市ID！','error');
		}
		$city_express = plugin('jy_weishop')->plugin_setting('citypeisong');
		$city=pdo_get('jy_huolala_city',array('uniacid'=>$_SESSION['uniacid'],'city_id'=>$basic['city_id']));
		if(!$city['id']){
			exi('货拉拉接口还未同步城市！','error');
		}
		if(!$basic['order_vehicle_id']){
			exi('请先填写车型ID：货拉拉接口-基本设置-车型ID！','error');
		}
		$lat_lon_arr=array();
		$addr_info=array();
		$total_price_fen=0;
		foreach($orders as $ov){
			$total_price_fen +=$ov['price'];
			if($ov['storeid']){
				$storeid=$ov['storeid'];
			}
		}
		//发货地址：
		if($storeid){
			$storeinfo=pdo_get('jy_weishop_store',array('uniacid'=>$_SESSION['uniacid'],'id'=>$storeid),array('lat_lng','pcd','mobile','realname','address'));
			$storeinfo['lat_lng']=$storeinfo['lat_lng']?json_decode($storeinfo['lat_lng'],true):array();
			$storeinfo['pcd']=$storeinfo['pcd']?json_decode($storeinfo['pcd'],true):array();
			$city_express['lat_lng']=$storeinfo['lat_lng']?:$city_express['lat_lng'];
			$city_express['pcd']=$storeinfo['pcd']?:$city_express['pcd'];
			$city_express['address']=$storeinfo['address'];
			$city_express['mobile']=$storeinfo['mobile'];
			$city_express['realname']=$storeinfo['realname'];
		}
		//如果是商户
		if($merchid){
			$merchinfo=pdo_get('jy_merch_user',array('id'=>$merchid),array('lat_lng','pcd','mobile','realname','address'));
			$merchinfo['lat_lng']=$merchinfo['lat_lng']?json_decode($merchinfo['lat_lng'],true):array();
			$merchinfo['pcd']=$merchinfo['pcd']?json_decode($merchinfo['pcd'],true):array();
			$city_express['lat_lng']=$merchinfo['lat_lng']?:$city_express['lat_lng'];
			$city_express['pcd']=$merchinfo['pcd']?:$city_express['pcd'];
			$city_express['address']=$merchinfo['address'];
			$city_express['mobile']=$merchinfo['mobile'];
			$city_express['realname']=$merchinfo['realname'];
		}
		$lat_lon_arr[]=array(
			'lat'=>$city_express['lat_lng']['lat'],
			'lon'=>$city_express['lat_lng']['lng'],
			'city_id'=>$city['city_id'],
		);
		$addr_info[]=array(
			'lat_lon'=>array('lat'=>$city_express['lat_lng']['lat'],'lon'=>$city_express['lat_lng']['lng']),
			'city_id'=>$city['city_id'],
			'addr'=>$city_express['pcd']['province'] . $city_express['pcd']['city'] . $city_express['pcd']['district'] . $city_express['pcd']['street'] . $city_express['address'],
			'name'=>$city_express['address'],
			'contact_name'=>$city_express['realname'],
			'contact_phone_no'=>$city_express['mobile'],
		);
		foreach($orders as $order){
			if($order['address'] && ($order['address']['address'] || $order['address']['mobile'])){
				$receiver=$order['address'];
				if(!is_array($receiver)){
    				$receiver=json_decode($receiver,true);
    			}
			}else{
				$receiver=pdo_get('core_address',array('id'=>$order['addressid'],'uniacid'=>$_SESSION['uniacid']));
			}
			if(!is_array($receiver['pcd'])){
				$receiver['pcd']=json_decode($receiver['pcd'],true);
			}
			$addressinfo=$receiver['pcd']['province'] . $receiver['pcd']['city'] . $receiver['pcd']['district'] . $receiver['pcd']['street'] . $receiver['address'];
			$receiver['lat_lng']=$receiver['lat_lng']?json_decode($receiver['lat_lng'],true):array();
			if($receiver['lat_lng']['lat']){
			    $location=$receiver['lat_lng'];
			}else{
		    	$location_data=cfc('tools')->getgeocode($addressinfo, $cityexpress['geo_key']);
		    	if ($location_data['status'] == 1 && 0 < $location_data['count']){
    				$location = explode(',', $location_data['geocodes'][0]['location']);
    			}else{
    			    $location = array();
    			    //print_r($location_data);exit;
    			}
			}
			$lat_lon_arr[]=array('lat'=>$location['lat'],'lon'=>$location['lng'],'city_id'=>$city['city_id']);
			$addr_info[]=array(
					'lat_lon'=>array('lat'=>$lat_lon_arr['lat'],'lon'=>$lat_lon_arr['lng']),
					'city_id'=>$city['city_id'],
					'addr'=>$addressinfo,
					'name'=>$receiver['address'],
					'contact_name'=>$receiver['name']?:$order['realname'],
					'contact_phone_no'=>$receiver['mobile']?:$order['mobile'],
			);
		}
		$post = array(
			'city_id' => $city['city_id'],
			'city_info_revision' => $city['revision'],
			'order_vehicle_id' =>$basic['order_vehicle_id'],
			'order_time' => time() + 600,
			'lat_lon_arr' => ijson_encode($lat_lon_arr),
		);
		$res=$this->request($api_method,$post);
		//print_r($res);exit;
		if($res['ret']){
			exi('获取计价失败：'.$res['ret'].','.$res['msg'],'error');
		}
		$res['data']['addr_info']=$addr_info;
		$res['data']['order_vehicle_id']=$post['order_vehicle_id'];
		$res['data']['total_price_fen']=$total_price_fen*100;
		return $res['data'];
	}
	public function order_send($order,$merchid=0,$ismore=false){
		$orderlist=array();
		if(!$ismore){
			$orderlist[]=$order;
		}else{
			$orderlist=$order;
		}
		$getdata=$this->get_price($orderlist,$merchid);
		//print_r($getdata);exit;
		$fahuoinfo=$getdata['addr_info'][0];
		$api_method = 'e-order-request';
		$data = array(
			'city_id' => $city['city_id'],
			'city_info_revision' =>$city['revision'],
			'order_vehicle_id' => $getdata['order_vehicle_id'],
			'contact_name' => $fahuoinfo['contact_name'],
			'contact_phone_no' =>$fahuoinfo['contact_phone_no'],
			'order_time' => time() + 600,
			'total_price_fen' => $getdata['total_price_fen'],
			'price_calculate_id' =>$getdata['price_calculate_id'],
			'pay_type' => 3,
			'addr_info' => ijson_encode($getdata['addr_info']),
			'outside_order_id' =>$orderlist[0]['ordersn'],
			'notify_url' => SITEROOT.'/addons/jy_huolala/notify.php'
		);
		$res=$this->request($api_method,$data);
		if ($ret['ret'] == 0) {
			return array('state' => 1, 'msg' => '发货成功','openorderid'=>$ret['data']['order_display_id']);
		}
		return array('state' => 0, 'msg' => $ret['msg']);
	}
	public function order_sendmore($orderlist,$merchid=0){
		$res=$this->order_send($orderlist,$merchid,true);
		return $res;
	}
	public function cancel_send($openorderid,$cancel_reason_id=0,$cancel_reason=''){
		$api_method = 'e-order-cancel';
		$data = array(
			'order_display_id' => $openorderid,
			'order_status' =>0,
			'reason_id' => 1,
			'reason' => $cancel_reason?:'计划有变，暂时不需要用车',
		);
		$res=$this->request($api_method,$data);
		if ($ret['ret'] == 0) {
			return array('state' => 1, 'msg' => '取消成功');
		}
		return array('state' => 0, 'msg' => $ret['msg']);
	}
	/*
		生成签名
	*/
	private function md5_sign($map,$app_secret=''){
		$rList = array();
		foreach($map as $k =>$v) {
			if ($k == "other_settle_params" || $k == "sign" || $k == "msg_signature" || $k == "thirdparty_id"){
				continue;
			}
			$value = trim(strval($v));
			$len = strlen($value);
			if ($len > 1 && substr($value, 0,1)=="\"" && substr($value,$len, $len-1)=="\""){
				$value = substr($value,1, $len-1);
			}
			$value = trim($value);
			if ($value == "" || $value == "null"){
				//continue;
			}
			$rList[]=$k;
		}
		sort($rList, 2);
		$data='';
		foreach($rList as $i=>$k){
		    if($data){
		        $data.='&'.$k.'='.$map[$k]; 
		    }else{
		        $data.=$k.'='.$map[$k]; 
		    }
		}
		$data.=$app_secret;
		//file_put_contents(ROOT_D.'/2.txt',$data);
		//print_r($data);exit;
		return md5($data);
	}
}